<template>
  <view class="dropdown-tree-selector">
    <view @click="toggleDropdown" class="dropdown-header">
      <view class="head-label">
        <view
          style="color: #aaaaaa"
          v-if="
            (multiple && selectedList.length === 0) ||
            (!multiple && !selectedLabel)
          "
        >
        <uni-easyinput
            v-if="isSearch"
            v-model="searchQuery"
            @input="filterTreeData"
            placeholder="请选择"
          />
          <span class="placeholder" v-else>{{ placeholder }}</span>
        </view>

        <view v-if="multiple && selectedList.length > 0">
          <span v-for="item in selectedList" :key="item.id" class="span-item">
            {{ item.label
            }}<uni-icons
              @click.native.stop="clearSelect($event, item)"
              type="clear"
              size="20"
              style="padding-left: 4px; color: rgb(144, 147, 153)"
            ></uni-icons>
          </span>
        </view>
        <view class="select-label" v-if="!multiple">
          {{ selectedLabel }}
        </view>

        <!-- {{ selectedLabel || placeholder }} -->
      </view>
      <view class="dropdown-icon">
        <image
        class="icon-down"
          v-if="multiple || (!multiple && !selectedLabel)"
          src="./../../static/images/icon/down.png"
          alt=""
        ></image>
        <uni-icons
          color="#c0c4cc"
          @click.native.stop="clearSelect($event)"
          v-if="!multiple && selectedLabel"
          type="closeempty"
          size="20"
        ></uni-icons>
      </view>
    </view>

    <view v-if="isOpen" class="dropdown-content">
      <tree-node
        v-for="node in filteredTreeData"
        :key="node.id"
        :node="node"
        :selectedIds="selectedIds"
        :multiple="multiple"
        @select="handleSelect"
      ></tree-node>
    </view>
  </view>
</template>

<script>
import TreeNode from "./tree-node.vue";

export default {
  components: {
    TreeNode,
  },
  props: {
    treeData: {
      type: Array,
      required: true,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: "请选择",
    },
    selectedIds: {
      type: [Array, String, Number],
      default: () => [],
    },

    isSearch: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      isOpen: false,

      selectedLabel: "",

      searchQuery: "",
      filteredTreeData: [],
      selectedList: [],
      localSelectedIds: [], // 本地存储 selectedIds 的副本
    };
  },
  watch: {
    treeData: {
      immediate: true,
      handler(newVal) {
        this.filteredTreeData = newVal;
      },
    },
    selectedIds: {
      immediate: true,
      handler(newVal) {
        this.localSelectedIds = newVal;
        this.updateSelectedList(newVal);
      },
    },
  },

  mounted() {
    this.updateSelectedList(this.localSelectedIds);
    document.addEventListener("click", this.closeDropdownOnClickOutside);
  },
  beforeDestroy() {
    document.removeEventListener("click", this.closeDropdownOnClickOutside);
  },
  methods: {
    updateSelectedList(newIds) {
      if (this.multiple && this.localSelectedIds) {
        this.selectedList = newIds.map((id) => this.findNodeById(id));
        this.selectedList = this.selectedList.filter((item) => item !== null);
      }
      if (!this.multiple && newIds) {
        this.selectedLabel = this.findNodeLabelById(newIds);
      }
    },
    closeDropdownOnClickOutside(event) {
      if (!this.$el.contains(event.target)) {
        this.isOpen = false;
      }
    },
    toggleDropdown() {
      this.isOpen = !this.isOpen;
    },
    clearSelect(event, item) {
      event.stopPropagation();
      if (this.multiple && item) {
        const index = this.selectedList.findIndex(
          (selectedItem) => selectedItem === item
        );
        if (index !== -1) {
          this.selectedList.splice(index, 1);
        }
        this.localSelectedIds = this.selectedList.map((i) => i.id === item.id);
      }
      if (!this.multiple) {
        this.localSelectedIds = [];
        this.selectedLabel = "";
      }
      this.$emit("select", this.localSelectedIds);
    },
    handleSelect(node) {
      console.log("handleSelect", this.multiple);
      if (this.multiple) {
        if (node.selectedIds && node.selectedIds.length > 0) {
          // 使用 Set 提高查找效率
          const selectedIdsSet = new Set(this.selectedIds);

          // 判断是否需要全选或取消全选
          const allSelected = node.selectedIds.every((id) =>
            selectedIdsSet.has(id)
          );

          if (allSelected) {
            // 取消全选
            node.selectedIds.forEach((id) => selectedIdsSet.delete(id));
          } else {
            // 全选
            node.selectedIds.forEach((id) => selectedIdsSet.add(id));
          }

          // 更新 this.selectedIds
          this.localSelectedIds = Array.from(selectedIdsSet);
          console.log(this.localSelectedIds, "this.localSelectedIds");
        } else {
          if (this.localSelectedIds.includes(node.id)) {
            this.localSelectedIds = this.selectedIds.filter(
              (id) => id !== node.id
            );
          } else {
            this.localSelectedIds.push(node.id);
          }
        }
        if (this.multiple) {
          this.selectedList = this.localSelectedIds.map((id) =>
            this.findNodeById(id)
          );
        }
      } else {
        this.localSelectedIds = node.id;
        // this.selectedLabel = node.label;
        this.selectedLabel = this.findNodeLabelById(node.id);

        this.isOpen = false;
      }
      this.$emit("select", this.localSelectedIds);
    },
    //根据id获取label 上级label/label
    // 根据id获取label及其上级label
    findNodeLabelById(id, nodes) {
      // 如果 nodes 未提供，则使用 this.treeData
      if (nodes === undefined) {
        nodes = this.treeData;
      }
      // 查找指定id的节点及其上级节点
      function findNode(node, id, pathLabels) {
        if (node.id === id) {
          return pathLabels.concat(node.label).join("/");
        }

        if (node.children && node.children.length > 0) {
          for (let child of node.children) {
            const result = findNode(child, id, pathLabels.concat(node.label));
            if (result) {
              return result;
            }
          }
        }
        return null;
      }
      try {
        // 从根节点开始查找
        const rootLabels = [];
        for (let rootNode of nodes) {
          const labelPath = findNode(rootNode, id, rootLabels);
          if (labelPath) {
            return labelPath;
          }
        }
        // 如果找不到对应id的节点，返回null
        return null;
      } catch (error) {
        console.error("Error finding node label by id:", error);
        return null;
      }
    },
    //根据id获取node
    findNodeById(id, nodes) {
      // 如果 nodes 未提供，则使用 this.treeData
      if (nodes === undefined) {
        nodes = this.treeData;
      }

      // 检查 id 和 nodes 是否有效
      if (id === null || id === undefined || !Array.isArray(nodes)) {
        return null;
      }

      // 遍历 nodes 查找匹配的节点
      for (let node of nodes) {
        if (node.id === id) {
          return node;
        }
        if (node.children && Array.isArray(node.children)) {
          const result = this.findNodeById(id, node.children);
          if (result) {
            return result;
          }
        }
      }

      // 如果没有找到匹配的节点，返回 null
      return null;
    },
    filterTreeData() {
      const query = this.searchQuery.toLowerCase();
      if (query) {
        this.filteredTreeData = this.treeData.filter((node) =>
          this.nodeMatchesQuery(node, query)
        );
      } else {
        this.filteredTreeData = this.treeData;
      }
    },
    nodeMatchesQuery(node, query) {
      if (node.label.toLowerCase().includes(query)) {
        return true;
      }
      if (node.children) {
        return node.children.some((child) =>
          this.nodeMatchesQuery(child, query)
        );
      }
      return false;
    },
  },
};
</script>

<style lang="scss" scoped>

@function pxtovw($px) {
  @return #{$px / 20 * 1}vw;
}
.dropdown-tree-selector {
  position: relative;
  width: 100%;
  border-radius: pxtovw(40);
}

.dropdown-header {

  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 pxtovw(30);
  border: pxtovw(1) solid #d9d9d9;
  width: 100%;
height: pxtovw(98);
background: #FFFFFF;
border-radius: pxtovw(20);
  cursor: pointer;
  background-color: #fff;
}
.dropdown-header:focus {
  border: 1rpx solid #30b3ab;
}

.dropdown-header:focus {
  border: 1px solid #409eff;
}
.head-label {


  white-space: nowrap;
  overflow: hidden;

}
.dropdown-icon {
  transform: rotate(0deg);
  transition: transform 0.3s ease;
}

.dropdown-content {
  width: pxtovw(600);

  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background-color: #fff;

  border-top: none;
  border-radius: 0 0 pxtovw(4) pxtovw(4);
  max-height: pxtovw(600);
  overflow-y: auto;
  z-index: 1000;
  box-sizing: border-box;

  left: 0;


  border: pxtovw(1) solid #ebeef5;

  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

 
}
.search-input {
  margin: 0rpx;

  /* border: 1px solid #ccc; */
  /* border-radius: 4px; */
  height: 100%;
  height: pxtovw(40);
}
.span-item {
  background-color: rgb(244, 244, 245);
  color: rgb(144, 147, 153);
  border: 1px solid rgb(233, 233, 235);
  margin: pxtovw(2) pxtovw(0) pxtovw(2) pxtovw(6);
  padding: pxtovw(6);

  border-radius: pxtovw(4);
}
.span-item:first-child {
  margin: pxtovw(2) pxtovw(0) pxtovw(2) pxtovw(0);
}
.span-item-null {
  padding: 0 pxtovw(6);
}
::v-deep .uni-easyinput__content-input{
    height: pxtovw(88);
  background: #FFFFFF;
  border-radius: pxtovw(20);
  }
  ::v-deep .uni-easyinput__placeholder-class{
    font-size: pxtovw(30);
    color: #AAAAAA;
  }
  ::v-deep{
    .uni-input-input{
      font-size: pxtovw(30);
    }
  }
  ::v-veep .content-clear-icon{
      font-size: pxtovw(24);
    }
    ::v-deep .is-input-border{
      border: 0;
    }
    .icon-down{
        width: pxtovw(36);
         height: pxtovw(36)
    }
    .select-label{

font-weight: 500;
font-size: pxtovw(30);
color: #666666


    }
    .placeholder{
      font-weight: 500;
font-size: pxtovw(30);
color: #AAAAAA;
    }
</style>
